const express = require('express');
const { getConfig, updateConfig } = require('../utils/config-manager');

const router = express.Router();

/**
 * @route GET /api/config
 * @desc 获取当前配置
 */
router.get('/', (req, res) => {
  try {
    const config = getConfig();

    // 创建一个不包含密钥的配置副本
    const safeConfig = { ...config };

    // 如果密钥存在，用星号替换部分内容
    if (safeConfig.alibaba_cloud_access_key_id) {
      const id = safeConfig.alibaba_cloud_access_key_id;
      safeConfig.alibaba_cloud_access_key_id_masked =
        id.substring(0, 3) + '****' + id.substring(id.length - 3);
    }

    if (safeConfig.alibaba_cloud_access_key_secret) {
      const secret = safeConfig.alibaba_cloud_access_key_secret;
      safeConfig.alibaba_cloud_access_key_secret_masked =
        secret.substring(0, 3) + '****' + secret.substring(secret.length - 3);
    }

    // 删除实际的密钥，只返回掩码版本
    delete safeConfig.alibaba_cloud_access_key_secret;
    delete safeConfig.alibaba_cloud_access_key_id;

    res.json({
      success: true,
      config: safeConfig
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * @route POST /api/config
 * @desc 更新配置
 */
router.post('/', (req, res) => {
  try {
    const {
      alibaba_cloud_access_key_id,
      alibaba_cloud_access_key_secret,
      bailian_api_endpoint,
      bailian_model_id,
      use_openai_client,
      use_official_api
    } = req.body;

    // 创建新的配置对象，只包含提供的字段
    const newConfig = {};

    if (alibaba_cloud_access_key_id !== undefined) {
      newConfig.alibaba_cloud_access_key_id = alibaba_cloud_access_key_id;
    }

    if (alibaba_cloud_access_key_secret !== undefined) {
      newConfig.alibaba_cloud_access_key_secret = alibaba_cloud_access_key_secret;
    }

    if (bailian_api_endpoint !== undefined) {
      newConfig.bailian_api_endpoint = bailian_api_endpoint;
    }

    if (bailian_model_id !== undefined) {
      newConfig.bailian_model_id = bailian_model_id;
    }

    // 处理新的配置字段
    if (use_openai_client !== undefined) {
      newConfig.use_openai_client = use_openai_client;
    }

    if (use_official_api !== undefined) {
      newConfig.use_official_api = use_official_api;
    }

    // 更新配置
    const updatedConfig = updateConfig(newConfig);

    // 创建一个不包含密钥的配置副本
    const safeConfig = { ...updatedConfig };

    // 如果密钥存在，用星号替换部分内容
    if (safeConfig.alibaba_cloud_access_key_id) {
      const id = safeConfig.alibaba_cloud_access_key_id;
      safeConfig.alibaba_cloud_access_key_id_masked =
        id.substring(0, 3) + '****' + id.substring(id.length - 3);
    }

    if (safeConfig.alibaba_cloud_access_key_secret) {
      const secret = safeConfig.alibaba_cloud_access_key_secret;
      safeConfig.alibaba_cloud_access_key_secret_masked =
        secret.substring(0, 3) + '****' + secret.substring(secret.length - 3);
    }

    // 删除实际的密钥，只返回掩码版本
    delete safeConfig.alibaba_cloud_access_key_secret;
    delete safeConfig.alibaba_cloud_access_key_id;

    res.json({
      success: true,
      message: '配置已更新',
      config: safeConfig
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * @route POST /api/config/test
 * @desc 测试当前配置
 */
router.post('/test', async (req, res) => {
  try {
    const { getBailianClient } = require('../utils/bailian-client-adapter');

    // 获取当前配置的客户端
    const client = getBailianClient();

    // 使用简单的提示测试 API
    const response = await client.generateCompletion('测试连接', 10, 0.7);

    res.json({
      success: true,
      message: 'API 连接测试成功',
      response
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

module.exports = { configRouter: router };
